<template>
    <!-- 整体容器 -->
    <div class="pages">
        <el-container class="page-container">
            <!-- 搜索 -->
            <el-header class="page-header">
                <el-space :size="10">
                    <el-select v-model="lookupData.status" placeholder="请选择广告状态" clearable>
                        <el-option v-for="(item,index) in adStatusMap" :key="index" :label="item.name"
                            :value="item.value" />
                    </el-select>
                    <el-select v-model="lookupData.type" placeholder="请选择广告类型" clearable>
                        <el-option v-for="(item,index) in adUnionTypeMap" :key="index" :label="item.name"
                            :value="item.value" />
                    </el-select>
                    <el-button type="primary" :icon="Search" @click="handlerLookupAdvertise">查找</el-button>
                    <el-button type="primary" :icon="Plus" @click="handlerAddAdvertise">添加</el-button>
                </el-space>
            </el-header>
            <el-main class="page-main">
                <!-- 表格 -->
                <div class="main-table">
                    <el-table :data="tableData" border style="width: 100%">
                        <el-table-column prop="id" label="广告ID" align="center" />
                        <el-table-column prop="title" label="广告标题" align="center" />
                        <el-table-column label="广告图片" align="center">
                            <template #default="scope">
                                <el-popover v-if="scope.row.type!=6&&scope.row.type!=9" placement="right" :width="300"
                                    :popper-style="'background-color:'+scope.row.color">
                                    <template #reference>
                                        <el-image style="height: 30px" :src="scope.row.imgUrl" fit="contain" />
                                    </template>
                                    <template #default>
                                        <div style="display: flex;align-items: center">
                                            <el-image :src="scope.row.imgUrl" fit="contain" />
                                        </div>
                                    </template>
                                </el-popover>
                                <el-tag v-else>类型无需照片</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="广告类型" align="center" width="140px">
                            <template #default="scope">
                                <el-tag>
                                    {{adTypeMap.find(item=>item.value == scope.row.type)?.name}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="广告状态" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.status==0?'danger':'success'">
                                    {{scope.row.status==0?'冻结':'激活'}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unionType" label="关联类型" align="center" width="100px">
                            <template #default="scope">
                                <el-tag type="warning">
                                    {{adUnionTypeMap.find(item=>item.value == scope.row.unionType)?.name}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
                        <el-table-column label="创建时间" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.gmtCreate">
                                    {{new Date(scope.row.gmtCreate).friendlyTime(1)}}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="160px">
                            <template #default="scope">
                                <el-button type="primary" @click="handlerEditAdvertise(scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handlerDeleteAdvertise(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="page-pagination">
                    <Pagination v-bind="advertisPaging" @handle-pagination="emitEntProps" />
                </div>
                
                <!-- 对话框 -->
                <!-- 当关闭 Dialog 时，销毁其中的元素-->
                <el-dialog v-model="dialogFormVisible" :title="refTitle" destroy-on-close @opened="heanlerOpenendDialog">
                    <el-form ref="ruleFormRef" :model="dialogForm" label-width="120px" :rules="rules"
                        label-position="left" style="padding:0px 50px">
                        <el-form-item label="广告标题" prop="title" class="is-required">
                            <el-input v-model="dialogForm.title" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="广告类型" prop="type" class="is-required">
                            <el-select v-model="dialogForm.type" placeholder="请选择"  @change="heanlerAdvertisType">
                                <el-option v-for="(item,index) in adTypeMap" :key="index" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="广告图片" v-if="unionData?.picReqquire" id="upload" ref="refDialog" prop="imgUrl">
                            <el-upload class="avatar-uploader" :headers="headers" :action="action.url"
                                :show-file-list="false" :on-success="handleAvatarSuccess">
                                <img v-if="dialogForm.imgUrl" :src="dialogForm.imgUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="广告状态" prop="status" class="is-required">
                            <el-switch v-model="dialogForm.status" :active-value="1" :inactive-value="0" class="ml-2"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </el-form-item>
                        <el-form-item label="关联状态" prop="unionType" class="is-required">
                            <el-select v-model="dialogForm.unionType " placeholder="请选择" @change="heanlerchan">
                                <el-option v-for="(item,index) in adUnionTypeMap" :key="index" :label="item.name"
                                    :value="item.value"
                                    :disabled='!unionData||!unionData.unionTypes?.includes(item.value)' />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品" v-if="dialogForm.unionType==1" prop="unionValue">
                            <el-cascader :options="cascaderCommodity" :props="commodityProps"
                                v-model="dialogForm.unionValue" />
                        </el-form-item>
                        <el-form-item label="类目" v-if="dialogForm.unionType==2" prop="unionValue">
                            <el-cascader :options="cascaderCategory" :props="categoryProps"
                                v-model="dialogForm.unionValue" />
                        </el-form-item>
                        <el-form-item label="关键字" v-if="dialogForm.unionType==3" prop="unionValue">
                            <el-input autocomplete="off" v-model="dialogForm.unionValue" />
                        </el-form-item>
                        <el-form-item label="功能页面" v-if="dialogForm.unionType==4" prop="unionValue">
                            <el-select placeholder="请选择" v-model="dialogForm.unionValue">
                                <el-option v-for="(item,index) in functionPages" :key="index" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ClassPagination, ClassAdvertisDialogForm } from '#/index';
import {theColorFn} from '@/utils/theColor'
import { reactive, ref, nextTick, computed } from "vue";
import { Search, Plus } from '@element-plus/icons-vue';
import { post } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from 'element-plus'
import type { UploadProps } from 'element-plus'
import cookie from "js-cookie"


const ruleFormRef = ref<FormInstance>()
// 获取请求头
const headers = reactive({
    AdminToken: cookie.get("token")
})
const action = reactive({
    url:process.env.NODE_ENV === 'development'?'/upload/admin':''
})
const refDialog = ref()
// 获取分页的数据
const advertisPaging = reactive(new ClassPagination())
// 搜索下拉框数据类型
const lookupData = reactive({
    status: '',
    type: ''
})
// 存储获取到的表格数据
const tableData: TypeAdvertis[] = reactive([])
// 6种广告类型
const adTypeMap = reactive([
    { value: 1, unionTypes: [1, 2, 3, 4], picReqquire: true, name: '轮播' },
    { value: 2, unionTypes: [2], picReqquire: true, name: '分类精选' },
    { value: 3, unionTypes: [1, 2, 3, 4], picReqquire: true, name: '横幅' },
    { value: 4, unionTypes: [1, 2, 3, 4], picReqquire: true, name: '首页轮播下5按钮' },
    { value: 6, unionTypes: [1, 2, 3, 4], picReqquire: false, name: '公告' },
    { value: 9, unionTypes: [1], picReqquire: false, name: '商品推荐' },
])
// 4种广告关联类型
const adUnionTypeMap = reactive([
    { value: 1, name: '商品' },
    { value: 2, name: '类目' },
    { value: 3, name: '关键字' },
    { value: 4, name: '功能页面' },
])
// 广告状态
const adStatusMap = reactive([
    { value: 0, name: '冻结' },
    { value: 1, name: '激活' },
])
//功能页面
const functionPages = reactive([
    { value: '/pages/product/groupshop', name: '团购列表' },
    { value: '/pages/coupon/list', name: '优惠券列表' },
])
// 对话框状态
const dialogFormVisible = ref(false)
// 对话框标题
const refTitle = ref("创建")
// 对话框数据类型
const dialogForm = reactive(new ClassAdvertisDialogForm())
// 获取商品树
const cascaderCommodity: Array<object> = reactive([])
// 下拉选择树，子级配置
const commodityProps = reactive({
    emitPath: false,//返回数字类型数据，true返回数组类型数据
    children: 'children',
    value: 'id',
    label: 'label',
})
/**
 * 存储类目树数据
 */
const cascaderCategory: Array<object> = reactive([])
/**
 * 存储类目树数据，规定子节点数据
 */
const categoryProps = reactive({
    emitPath: false,//返回数字类型数据，true返回数组类型数据
    checkStrictly: true,
    children: 'childrenList',
    value: 'id',
    label: 'title',
})
// 获取对话框数据类型空值
const dialogFormNull = { ...dialogForm }
// 计算属性
let unionData = computed(() => {
    if (dialogForm.type) {
        return adTypeMap.find(item => item.value == dialogForm.type)
    } else {
        return ''
    }
})


//验证规则
const rules = reactive({
    title: [{ required: true, message: '请输入广告标题', trigger: 'blur' }],
    type: [{ required: true, message: '请选择广告类型', trigger: 'change' },],
    unionType: [{ required: true, message: '请选择关联类型', trigger: 'blur' }],
    unionValue: [{ required: true, message: '不能为空', trigger: 'blur' }],
    imgUrl: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
})
// 上传头像
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    res, uploadFile
) => {
    dialogForm.imgUrl = res.url
    if (200 == res.errno) {
        dialogForm.imgUrl = res.url // 得到上传图片成功的路径
        theColorFn(dialogForm.imgUrl, (callback: string) => {
            dialogForm.color = callback
        }) // 计算得到图片平均色
        getInitAdvertise()  //初始化
    }
}
/**
 * 确定添加广告
 */
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                _gp: 'admin.advert',
                _mt: refTitle.value == "创建" ? 'create' : 'edit',
                ...dialogForm
            }
            if(data.type > 4){
                data.imgUrl = "http://img.zxwyit.com/admin.shopmall.com/d2a9432712b24a9fa3c012ef1b4e190d.png"
                data.color = 'rgb(255,255,255)'
            }
            post(data).then((res) => {
                if (200 === res.errno) {
                    ElMessage.success(refTitle.value == "创建" ? "添加成功" : "修改成功")
                    dialogFormVisible.value = false
                    getInitAdvertise()
                } else {
                    ElMessage.warning(res.errmsg)
                }
            })
        } else {
            return false
        }
    })
}
// 清空
function heanlerchan() {
    dialogForm.unionValue = ''
}
/**
* 商品树形数据
*/
function getCommodity() {
    let data = {
        _gp: 'admin.product',
        _mt: 'getSpuBigTree'
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            cascaderCommodity.length = 0
            cascaderCommodity.push(...res.data)
        }
    })
}
/**
* 获取类目树数据
*/
function getCategory() {
    let data = {
        _gp: 'admin.category',
        _mt: 'categoryTree'
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            cascaderCategory.length = 0
            cascaderCategory.push(...res.data)
        }
    })
}
// 如果已经请求了那么就不用重复请求
if (cascaderCommodity.length <= 0 && cascaderCategory.length <= 0) {
    getCommodity()//商品树形数据
    getCategory()//获取类目树数据
}
/**
 * 获取表格数据
 */
function getInitAdvertise() {
    let data = {
        _gp: 'admin.advert',
        _mt: 'list',
        type: lookupData.type,
        pageNo: advertisPaging.page,
        limit: advertisPaging.limit,
        status: lookupData.status,
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            let { items, total } = res.data
            tableData.length = 0
            tableData.push(...items)
            advertisPaging.total = total
        } else {
            tableData.length = 0
            ElMessage.warning(res.errmsg)
        }
    })
}
/**
 * 选择商品类型的cheage事件
 */
function heanlerAdvertisType() {
    nextTick(()=>{
        let dialog = document.getElementById("upload")
        if(dialog){
            dialog.style.backgroundColor = dialogForm.color
        }
    })
    dialogForm.unionType = ''
}
/**
 * 添加广告
 */
function handlerAddAdvertise() {
    refTitle.value = "创建"
    // 替换为空
    Object.assign(dialogForm, dialogFormNull)
    // 等待节点渲染完成，在进行弹出框显示
    nextTick(() => {
        dialogFormVisible.value = true
    })
}
/**
 * 查找广告
 */
function handlerLookupAdvertise() {
    advertisPaging.page = 1
    getInitAdvertise()
}
/**
 * 编辑广告
 */
function handlerEditAdvertise(row: TypeAdvertis) {
    console.log(row);
    
    refTitle.value = "编辑"
    if (row.unionType != 3 && row.unionType != 4) {
        row.unionValue = parseInt(row.unionValue as unknown as string)
    }
    // 替换为row数据
    Object.assign(dialogForm, row)
    if(dialogForm.type > 4){
        dialogForm.imgUrl = '' //清空图片
        dialogForm.color = ''   //清空颜色
    }
    dialogForm.adId = row.id
    nextTick(() => {
        dialogFormVisible.value = true
    })
}
/**
 * 删除广告
 */
function handlerDeleteAdvertise(row: TypeAdvertis) {
    ElMessageBox.confirm(
        '确认是否删除?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
    ).then(() => {
        post({
            _gp: 'admin.advert',
            _mt: 'delete',
            type: row.type,
            adId: row.id,
        }).then(res => {
            if (200 === res.errno) {
                getInitAdvertise()
                ElMessage.success("删除成功")
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }).catch(() => {
        ElMessage.warning("已取消删除")
    })
}
// 点击编辑获取节点并赋值颜色
function heanlerOpenendDialog() {
    if(dialogForm.type <= 4 && refTitle.value == "编辑"){
        refDialog.value.$el.style.background = dialogForm.color
    }
}
/**
 * 分页组件传递过来的数据
 * @param val
 * page:页数
 * limit:条数
 */
function emitEntProps(val: { page: number, limit: number }) {
    let paging = advertisPaging
    paging.page = val.page
    paging.limit = val.limit
    getInitAdvertise()
}

// 第一次请求表格数据
getInitAdvertise()
</script>

<style scoped lang="less">
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>